package com.iris.live.services.services.impl;

import com.iris.live.services.common.UserUtils;
import com.iris.live.services.data.models.用户Model;
import com.iris.live.services.data.models.销售顾问分组Model;
import com.iris.live.services.data.repositories.*;
import com.iris.live.services.models.PageData;
import com.iris.live.services.models.ResultData;
import com.iris.live.services.services.SalesSetService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

@Service
@Transactional
public class SalesSetServiceImpl implements SalesSetService {
    private static Logger logger = LoggerFactory.getLogger(SalesSetServiceImpl.class);

    @Autowired
    private SalesSetRepository salesSetRepository;

    @Autowired
    private 用户Repository userRepository;

    @Autowired
    private FileRepository fileRepository;

    @Autowired
    private 销售顾问分组Repository saleGWRepository;

    @Autowired
    private 销售顾问头像Repository saleGWTXRepository;


    @Override
    public List getFunctionList(String permit) {
        return salesSetRepository.getFunctionList(permit);
    }

    @Override
    public List getBrand() {
        return salesSetRepository.getBrand();
    }

    @Override
    public ResultData saveSaleConsultant(用户Model model) {
        //boolean flag;
        ResultData data = new ResultData();
        try {
            用户Model user = userRepository.findByYonghumingUserNameDelete(model.get用户名());
            if(user!=null){
                data.setMessage("该用户名已被占用，无法创建。");
                data.setResult("false");
                return data;
            }
            String checkedSuperior = UserUtils.superiorCheck(model.getSuperior());
            if (checkedSuperior == null) {
                data.setMessage("所属上级不存在或所属上级已离职");
                data.setResult("false");
                return data;
            } else {
                String blank = model.get用户名();
                boolean bool = blank.contains(" ");
                if (bool){
                    String User = blank.replace(" ","");
                    model.set用户名(User);
                    logger.info("您输入的用户名有空格，blank{},示例：User{}",blank,User);
                }
                if (model.get用户名().length()>35){
                    data.setResult("false");
                    data.setMessage("用户名不能超过30个字符");
                    return data;
                }
                if (model.get人员电话().length()!=11){
                    data.setResult("false");
                    data.setMessage("请输入正确的手机号码，手机号长度11位");
                    return data;
                }
                userRepository.save(model);
                data.setResult("true");
                data.setMessage("更新成功");
            }
        } catch (Exception e) {
            logger.error("销售顾问" + model.get用户名() + "数据保存异常。", e);
            data.setResult("false");
            data.setMessage("数据保存异常");
        }
        return data;
    }

    @Override
    public boolean updSaleConsultant(UpdSaleConsultantRequest request) {
        boolean flag;
        String checkedSuperior = UserUtils.superiorCheck(request.superior);
        if (checkedSuperior == null) {
            return false;
        } else {
            try {
                userRepository.updSaleConsultant(request.人员姓名, request.人员电话, request.品牌,
                        request.接待, request.用户名, request.职位, request.superior, request.销售顾问职位状态);
                flag = true;
            } catch (Exception e) {
                logger.error("销售顾问" + request.用户名 + "更新异常。", e);
                flag = false;
            }
            return flag;
        }
    }

    @Override
    @Transactional
    public boolean saveSaleConsultantGroup(销售顾问分组Model model) {
        boolean flag;
        try {
            if (model.get组名() != null && !"".equals(model.get组名())) {
                销售顾问分组Model m = saleGWRepository.findByPermitAndSc(model.get许可(), model.get销售顾问());
                if (m != null) {
                    m.set组名(model.get组名());
                    saleGWRepository.save(m);
                } else {
                    saleGWRepository.save(model);
                }
            } else {
                saleGWRepository.delSaleConsultantGruop(model.get销售顾问());
            }
            flag = true;
        } catch (Exception e) {
            logger.error("数据保存异常。", e);
            flag = false;
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return flag;
    }

    @Override
    public boolean updSaleConsultantGruop(UpdSaleConsultantGruopRequest request) {
        boolean flag;
        try {
            saleGWRepository.updSaleConsultantGruop(request.组名, request.销售顾问);
            flag = true;
        } catch (Exception e) {
            logger.error("数据更新异常。", e);
            flag = false;
        }
        return flag;
    }

    @Override
    public boolean delSaleConsultant(DelSaleConsultantRequest request) {
        boolean flag;
        try {
            userRepository.delSaleConsultantGruop(request.用户名);
            flag = true;
        } catch (Exception e) {
            logger.error("数据删除异常。", e);

            flag = false;
        }
        return flag;
    }

    @Override
    public boolean delSaleConsultantGruop(DelSaleConsultantGruopRequest request) {
        boolean flag;
        try {
            saleGWRepository.delSaleConsultantGruop(request.销售顾问);
            flag = true;
        } catch (Exception e) {
            logger.error("数据删除异常。", e);
            flag = false;
        }
        return flag;
    }

    @Override
    public String saveSaleCOnsultantHeadPhoto(InputStream inputStream, String originalFilename, String permit, String userName) {
        String path = null;
        try {
            path = this.fileRepository.save(inputStream, originalFilename);
            用户Model userModel = userRepository.findOne(userName);
            if (null == userModel) {
                return null;
            }
            userModel.set销售顾问头像路径(path);
            userRepository.save(userModel);
        } catch (Exception e) {
            logger.error("数据保存异常。", e);
        }
        return path;
    }

    @Override
    public boolean delSaleCOnsultantHeadPhoto(DelSaleCOnsultantHeadPhotoRequest request) {
        boolean flag;
        try {
            saleGWTXRepository.delSaleCOnsultantHeadPhoto(request.销售顾问用户名);
            flag = true;
        } catch (Exception e) {
            logger.error("数据删除异常。", e);
            flag = false;
        }
        return flag;
    }

    @Override
    public ResultData resetSalePwd(String saleUser) {
        ResultData rd = new ResultData();
        String msg = "修改成功";
        String flag = "true";
        try {
            userRepository.updateActiveUserNoPermit(saleUser, "111111");


        } catch (Exception e) {
            logger.error("销售顾问密码重置失败", e);
            msg = "重置失败";
            flag = "false";
        }
        rd.setMessage(msg);
        rd.setResult(flag);

        return rd;

    }
    /**
     *获取销售类型列表（数据字典）
     */
    @Override
    public ResultData getSaletype(){
        ResultData result = new ResultData();
        PageData page = new PageData();
        String msg = "查询成功";
        String flag = "true";
        try{
           List list =  salesSetRepository.getSaletype();
            if (list!=null){
                page.setTotal(list.size());
                page.setData(list);
            }
                result.setPageData(page);
                result.setResult("true");
                result.setMessage("查询成功");

        }catch (Exception e){
            logger.error("销售类型获取失败", e);
            msg = "查询失败";
            flag = "false";
        }
    return result;
    }


}
